package com.fzy.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/UpdateNewsServlet")
public class UpdateNewsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UpdateNewsServlet()
    {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");

        request.setCharacterEncoding("UTF-8");

        try {
            // 加载 MySQL 数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接，指定数据库 URL、用户名和密码
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/news?useUnicode=true&characterEncoding=utf-8", "root", "13100140892Fzy!");
            // 准备预编译的 SQL 删除语句
            PreparedStatement pst = conn.prepareStatement("SELECT * FROM news_table WHERE id = ?");
            System.out.println("修改新闻"+request.getParameter("id"));
            // 设置 SQL 语句中的参数，将请求参数中的 id 转换为整数并设置到第一个参数位置
            int id = Integer.parseInt(request.getParameter("id"));
            pst.setInt(1,id);
            // 执行查询
            ResultSet rs = pst.executeQuery();
            // 获取用于向客户端输出文本的字符输出流
            PrintWriter out = response.getWriter();
            if(rs.next()){
                String title = rs.getString("title");
                String author = rs.getString("author");
                String date = rs.getString("date");
                int heat = rs.getInt("heat");
                out.print("<form action='DoUpdateNewsServlet?id=" + id + "' method='post'>");
                out.print("新闻标题:");
                out.print("<input type='text' name='title' value='" + title + "'><br>");
                out.print("新闻作者:");
                out.print("<input type='text' name='author' value='" + author + "'><br>");
                out.print("新闻日期:");
                out.print("<input type='text' name='date' value='" + date + "'><br>");
                out.print("新闻热度:");
                out.print("<input type='text' name='heat' value='" + heat + "'><br>");
                out.print("<input type='submit' value='提交修改'>");
                out.print("</form>");
            }
            else{
                out.print("没有此新闻");
            }
        } catch (Exception e) {
            // 捕获并打印异常堆栈信息
            e.printStackTrace();
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    }

}
